package com.fiberhome.nas.feature.main.view


import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.fiberhome.nas.core.designsystem.component.SpaceBetweenRow
import com.fiberhome.nas.core.designsystem.theme.AppTheme
import com.fiberhome.nas.feature.main.R
import com.fiberhome.nas.feature.main.model.TabDestination
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch


// 数据模型
data class PhotoItem(
    val date: String,
    val images: List<Painter>
)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AiMainScreen(
    onBackClick: () -> Unit = {},
    modifier: Modifier = Modifier
) {

    // 模拟数据
    val demoPhotos = listOf(
        PhotoItem(
            date = "2025-3-26",
            images = listOf(
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay), // 需要替换为实际资源
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
            )
        ),
        PhotoItem(
            date = "2025-3-20",
            images = listOf(
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay)
            )
        ),
        PhotoItem(
            date = "2025-2-20",
            images = listOf(
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
            )
        ),
        PhotoItem(
            date = "2025-2-21",
            images = listOf(
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
                painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay),
            )
        )


    )
    val scope = rememberCoroutineScope()
    var selectedTabIndex by remember { mutableIntStateOf(0) }
    val pagerState = rememberPagerState { TabDestination.entries.size }
    val tabTitles = listOf("照片", "相册", "文件")

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("NAS 家庭储存") },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = { /* 存储空间操作 */ }) {
                        Icon(
                            imageVector = Icons.Default.DateRange,
                            contentDescription = "云存储"
                        )
                    }
                    IconButton(onClick = { /* 设置操作 */ }) {
                        Icon(
                            imageVector = Icons.Default.Settings,
                            contentDescription = "设置"
                        )
                    }
                }
            )
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = { /* 添加文件操作 */ },
                shape = CircleShape,
                containerColor = Color(0xFFFF5722), // 橙色按钮
                modifier = Modifier.size(56.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.Add,
                    contentDescription = "添加",
                    tint = Color.White
                )
            }
        }
    ) { paddingValues ->
        Column(
            modifier = modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            // 声明共享的滚动状态
            val gridState = rememberLazyGridState()
            // 存储状态卡片 - 添加滚动显示/隐藏功能
            var isVisible by remember { mutableStateOf(true) }
            // 监听滚动状态变化
            var previousIndex by remember { mutableIntStateOf(0) }
            var previousOffset by remember { mutableIntStateOf(0) }
            LaunchedEffect(gridState) {
                snapshotFlow {
                    Pair(
                        gridState.firstVisibleItemIndex,
                        gridState.firstVisibleItemScrollOffset
                    )
                }.distinctUntilChanged()
                    .collect { (currentIndex, currentOffset) ->
                        delay(2000)
                        isVisible = !isVisible
//
//
//                        val scrollThreshold = 5
//                        val isScrollingDown = currentOffset > previousOffset
//
//                        isVisible = !isScrollingDown
//                        previousIndex = currentIndex
//                        previousOffset = currentOffset
                    }
            }

            // 带动画的存储状态卡片
            AnimatedVisibility(
                visible = isVisible,
                enter = fadeIn() + slideInVertically(initialOffsetY = { -it }),
                exit = fadeOut() + slideOutVertically(targetOffsetY = { -it }),
            ) {
//                FakeImage()
                StorageStatusCard(
                    usedStorage = 1350,
                    totalStorage = 25600,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                )
            }

            // 标签页
            ScrollableTabRow(
                selectedTabIndex = pagerState.currentPage,
                containerColor = Color.Transparent,
                contentColor = MaterialTheme.colorScheme.onBackground,
                indicator = {
                    // 自定义指示器
                    Box(
                        modifier = Modifier
                            .tabIndicatorOffset(it[pagerState.currentPage])
                            .height(2.dp)
                            .background(
                                Color(0xFFFF5722),
                                RoundedCornerShape(topStart = 2.dp, topEnd = 2.dp)
                            )
                    )
                }
            ) {
                tabTitles.forEachIndexed { index, title ->
                    Tab(
                        selected = pagerState.currentPage == index,
                        onClick = {
                            scope.launch {
                                pagerState.scrollToPage(page = index)
                            }
                        },
                        text = {
                            Text(
                                text = title,
                                fontSize = 16.sp,
                                fontWeight = if (pagerState.currentPage == index) FontWeight.Bold else FontWeight.Normal
                            )
                        },
                        selectedContentColor = Color(0xFFFF5722),
                        unselectedContentColor = MaterialTheme.colorScheme.onBackground
                    )
                }
            }

            // 内容区域
            HorizontalPager(
                state = pagerState,
                modifier = Modifier.fillMaxSize()
            ) {
                when (it) {
                    0 -> PhotosContent(
                        gridState = gridState,
                        photos = demoPhotos
                    )

                    1 -> PlaceholderContent(text = "相册功能开发中")
                    2 -> PlaceholderContent(text = "文件功能开发中")
                }
            }
        }
    }
}

@Composable
private fun FakeImage() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(120.dp)
            .clipToBounds(),
        contentAlignment = Alignment.Center
    ) {
        Image(
            painter = painterResource(id = R.drawable.ic_github),
            contentDescription = "假图片",
            modifier = Modifier
                .size(100.dp)
                .padding(16.dp)
        )
    }
}


@Composable
private fun StorageStatusCard(
    usedStorage: Int,
    totalStorage: Int,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier,
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 存储图标
            Box(
                modifier = Modifier
                    .size(48.dp)
                    .background(Color(0xFFE3F2FD), RoundedCornerShape(8.dp))
                    .padding(8.dp),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    painter = painterResource(id = com.fiberhome.nas.core.ui.R.drawable.ic_alipay), // 需要替换为实际资源
                    contentDescription = "存储",
                    tint = Color(0xFF1976D2),
                    modifier = Modifier.size(24.dp)
                )
            }

            Spacer(modifier = Modifier.width(16.dp))

            // 存储信息
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = "${usedStorage}/${totalStorage} GB",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold
                )
                Spacer(modifier = Modifier.height(4.dp))
                // 进度条
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(6.dp)
                        .background(Color.LightGray, RoundedCornerShape(3.dp))
                ) {
                    Row(
                        modifier = Modifier.fillMaxHeight()
                    ) {
                        Box(
                            modifier = Modifier
                                .weight(usedStorage.toFloat() / totalStorage)
                                .background(
                                    Color(0xFFFF5722),
                                    RoundedCornerShape(topStart = 3.dp, bottomStart = 3.dp)
                                )
                        )
                        Box(
                            modifier = Modifier
                                .weight((totalStorage - usedStorage).toFloat() / totalStorage)
                        )
                    }
                }
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "照片 视频 文件",
                    fontSize = 12.sp,
                    color = Color.Gray
                )
            }

            // 云同步状态
            Column(
                horizontalAlignment = Alignment.End
            ) {
                Text(
                    text = "1030/TT",
                    fontSize = 12.sp,
                    color = Color.Gray
                )
                Text(
                    text = "云盘",
                    fontSize = 12.sp,
                    color = Color(0xFF1976D2)
                )
            }
        }
    }
}

@Composable
private fun SortContent() {
    SpaceBetweenRow(Modifier.padding(end = 8.dp)) {
        // 第一个Text：居中显示
        Text(
            text = "照片0 / 视频2",
            modifier = Modifier.weight(1f), // 占据剩余空间
            textAlign = TextAlign.Center
        )

        // 第二个Image：右对齐
        Image(
            painter = painterResource(id = R.drawable.ic_pay), // 替换为实际图片资源
            contentDescription = "示例图片",
            modifier = Modifier.size(24.dp) // 控制图片大小
        )
    }
}

@Composable
private fun PhotosContent(photos: List<PhotoItem>, gridState: LazyGridState) {
    LazyVerticalGrid(
        state = gridState,
        columns = GridCells.Fixed(4),
        modifier = Modifier.fillMaxSize(),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
        contentPadding = PaddingValues(16.dp)
    ) {
        stickyHeader {
            SortContent()
        }
        photos.forEach { photoSection ->
            // 日期标题 - 跨越4列
            item(span = { GridItemSpan(4) }) {
                Text(
                    text = photoSection.date,
                    fontSize = 14.sp,
                    color = Color.Gray,
                    modifier = Modifier.padding(0.dp, 8.dp, 0.dp, 8.dp)
                )
            }
            // 照片网格项
            items(photoSection.images) { resId ->
                Box(
                    modifier = Modifier
                        .aspectRatio(1f)
                        .clip(RoundedCornerShape(8.dp))
                        .background(Color.LightGray)
                ) {
                    Image(
                        painter = resId,
                        contentDescription = null,
                        contentScale = ContentScale.Crop,
                        modifier = Modifier.fillMaxSize()
                    )
                }
            }
        }
    }
}

@Composable
private fun PlaceholderContent(text: String) {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = text,
            fontSize = 18.sp,
            color = Color.Gray
        )
    }
}

@Preview
@Composable
fun AiMainScreenPreview() {
    AppTheme {
        Surface {
            AiMainScreen()
        }
    }
}